package com.example.sys.org.service;

import com.example.core.mapping.BaseMapping;
import com.example.core.service.BaseTreeServiceImpl;
import com.example.sys.org.constant.OrgConstant;
import com.example.sys.org.dao.SysDeptDao;
import com.example.sys.org.mapping.SysDeptMapping;
import com.example.sys.org.po.SysDept;
import com.example.sys.org.po.SysElement;
import com.example.sys.org.vo.SysDeptVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

@Service
public class SysDeptServiceImpl extends BaseTreeServiceImpl<SysDeptDao, SysDept, SysDeptVo> implements SysDeptService, SysElementRelationService {

    private SysElementService sysElementService;

    public SysElementService getSysElementService() {
        if (sysElementService == null) {
            sysElementService = getApplicationContext().getBean(SysElementService.class);
        }
        return sysElementService;
    }

    @Override
    public Class<? extends BaseMapping> getMappingClass() {
        return SysDeptMapping.class;
    }

    @Override
    public List<String> getElementAuthList(String userId) {
        SysElement sysElement = getSysElementService().getById(userId);
        return Arrays.asList(sysElement.getParentId());
    }


    @Override
    public String add(SysDept po) throws Exception {
        String id = super.add(po);
        SysElement sysElement = new SysElement();
        sysElement.setType(OrgConstant.DEPT);
        BeanUtils.copyProperties(po, sysElement);
        sysElement.setId(id);
        getSysElementService().add(sysElement);
        return id;
    }

    @Override
    public String update(SysDeptVo vo) throws Exception {
        SysElement sysElement = getSysElementService().getById(vo.getId());
        sysElement.setParentId(vo.getParentId());
        sysElement.setParentName(vo.getParentName());
        sysElement.setHierarchy(vo.getHierarchy());
        sysElement.setName(vo.getName());
        getSysElementService().saveOrUpdate(sysElement);
        return super.update(vo);
    }

    @Override
    public void delete(String id) throws Exception {
        super.delete(id);
        getSysElementService().delete(id);
    }
}
